package com.lill.system.web;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lill.common.component.util.R;
import com.lill.common.component.util.ShiroUtils;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.constant.SystemConstant;
import com.lill.system.model.SysUserEntity;
import com.lill.system.service.IKaptchaService;

@Controller
public class SysPageController {

	private final static Logger logger = LoggerFactory.getLogger(SysPageController.class);
	
	@Autowired
	private IKaptchaService kaptchaService; 
	
	@RequestMapping("{module}/{url}.html")
	public String page(@PathVariable("module") String module, @PathVariable("url") String url) {
		return "pages/" + module + "/" + url + ".html";
	}
	
	@RequestMapping("login.html")
	public String login() {
        return "login.html";
	}
	
	@RequestMapping("index.html")
	public String index() {
		return "index.html";
	}
	
	/*@GetMapping("/stat")
    public Object druidStat() {
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }*/
	
	@RequestMapping("isSysUser")
	@ResponseBody
	public R isSysUser(@CurrentUser SysUserEntity curUser) {
		if (SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
    		return R.ok().put("isAdmin", true);
    	}else{
    		return R.ok().put("isAdmin", false);
    	}
	}

	@RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码

        String text=kaptchaService.getkaptcha();
        //生成图片验证码
        BufferedImage image = kaptchaService.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute("KAPTCHA_SESSION_KEY", text);
        try {
			ServletOutputStream out = response.getOutputStream();
			ImageIO.write(image, "jpg", out);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
    }
	
    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public R login(String username, String password, String captcha) {
        String kaptcha = ShiroUtils.getKaptcha("KAPTCHA_SESSION_KEY");
        if (null == kaptcha) {
            return R.error("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return R.error("验证码不正确");
        }

        try {
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error(e.getMessage());
        } catch (LockedAccountException e) {
            return R.error(e.getMessage());
        } catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
        
        return R.ok();
    }
    
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        try {
        	Subject subject=SecurityUtils.getSubject();
        	subject.getSession().removeAttribute(SystemConstant.CURRENT_USER);
        	subject.logout();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
        return "redirect:/";
    }
}
